package com.yh.tea.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yh.tea.entity.Role;
import com.yh.tea.entity.User;
import com.yh.tea.mapper.RoleMapper;
import com.yh.tea.model.PageDTO;
import com.yh.tea.model.RoleQuery;
import com.yh.tea.model.RoleVO;
import com.yh.tea.model.UserVO;
import com.yh.tea.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yh.tea.utiity.ResponseResult;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yh
 * @since 2024-02-16
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public ResponseResult getRoleList(RoleQuery query) {
        // 1. 准备分页查询条件
        // 1.1.分页条件
        Page<Role> page = Page.of(query.getPageNo(), query.getPageSize());
        // 1.2.排序条件
        if(query.getSortBy().isEmpty()){
            // 如果排序字段为空，按照更新时间排序
            page.addOrder(new OrderItem("update_time", false));
        } else {
            page.addOrder(new OrderItem(query.getSortBy(), query.getIsAsc()));
        }
        //模糊查询寻
        if(query.getRoleName().isEmpty()){
            this.page(page);

        }else {
            this.page(page,new QueryWrapper<Role>().like("role_name",query.getRoleName()));
        }
        // 2. 查询，查询的接口将封装到 page 对象中。
        // 3. 数据非空校验
        List<Role> roles = page.getRecords();

        if(roles == null || roles.isEmpty()){
            return ResponseResult.success("",new PageDTO<RoleVO>(page.getPages(),page.getTotal(),new ArrayList()));
        }
        // 4. 存在数据，进行实体类转换
        List<RoleVO> roleVOList=new ArrayList();
        for (Role role : roles) {
            roleVOList.add(new RoleVO(role.getId(),role.getRoleName(),role.getDescription()));
        }
        // 5. 封装返回结果
        return ResponseResult.success("",new PageDTO<RoleVO>(page.getTotal(),page.getPages(),roleVOList));
    }

    @Override
    public ResponseResult getRoleByIds(List<Long> roleIdList) {
        return ResponseResult.success("查询成功",listByIds(roleIdList));
    }
}
